<template>
  <div class="container">
    <!-- 查询条件表单 -->
    <div class="query-form">
      <a-form ref="formRef" :model="queryForm" label-align="left" auto-label-width>
        <a-row justify="start" :gutter="16">
          <a-col :span="6">
            <a-form-item field="name" :label="$t('workflow.processDefinition.columns.processDefinitionName')">
              <a-input v-model="queryForm.name"
                :placeholder="$t('common.inputPlaceholder') + $t('workflow.processDefinition.columns.processDefinitionName')" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="key" :label="$t('workflow.processDefinition.columns.key')">
              <a-input v-model="queryForm.key"
                :placeholder="$t('common.inputPlaceholder') + $t('workflow.processDefinition.columns.key')" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="status" :label="$t('common.status')">
              <a-select v-model="queryForm.status" allow-clear :options="statusOption"
                :placeholder="$t('common.selectPlaceholder') + $t('common.status')" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div>
        <!-- 查询按钮 -->
        <a-button-group>
          <a-button type="primary" @click="search">{{ t('common.search') }}</a-button>
          <a-button @click="clear">{{ t('common.clear') }}</a-button>
        </a-button-group>
      </div>
    </div>

    <!-- 表格 -->
    <a-table row-key="id" :data="tableData" :loading="loading" :pagination="false" :row-selection="rowSelection"
      @selection-change="onSelectionChange">
      <template #columns>
        <a-table-column :title="$t('workflow.processDefinition.columns.key')" data-index="key" />
        <a-table-column :title="$t('workflow.processDefinition.columns.processDefinitionName')" data-index="name" />
        <a-table-column :title="$t('workflow.processDefinition.columns.version')" data-index="version">

          <!-- <template #cell="{ record }">
            <a-select v-model="record.id" :options="getVersionOptions(record.historyList)" />
          </template> -->
        </a-table-column>
        <a-table-column :title="$t('common.status')" data-index="suspensionState">
          <template #cell="{ record }">
            <a-switch v-model="record.suspensionState" :checked-value="1" :unchecked-value="2"
              @change="handleChangeStatus(record)" />
          </template>
        </a-table-column>
        <!-- <a-table-column :title="$t('workflow.processDefinition.columns.source')" data-index="source" /> -->
        <!-- <a-table-column :title="$t('workflow.processDefinition.columns.resourceName')" data-index="resourceName">
          <template #cell="{ record }">
            <a-tag>{{ record.resourceName }}</a-tag>
          </template>
</a-table-column> -->
        <a-table-column :title="$t('common.optional')" align="center" fixed="right">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" v-if="record.suspensionState == 1" size="small"
                :title="$t('workflow.processDefinition.actions.start')" @click="openProcessModel(record)">
                <icon-caret-right />
              </a-button>
              <a-button type="text" size="small" :title="$t('common.view')" @click="handleView(record)">
                <icon-eye />
              </a-button>
              <a-button type="text" size="small" :title="$t('common.edit')" @click="handlEdit(record)">
                <icon-edit />
              </a-button>
              <a-button type="text" size="small" :title="$t('common.exportFile')" @click="handleDownload(record)">
                <icon-download />
              </a-button>
              <a-popconfirm :content="$t('common.deleteTip')" @ok="handleDelete(record)">
                <a-button type="text" size="small" :title="$t('common.remove')" status="danger">
                  <icon-delete />
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
      <template #footer>
        <div class="table-footer">
          <a-button-group>
            <a-button type="primary" @click="openEditModal()">
              <template #icon>
                <icon-plus />
              </template>
              {{ t('common.add') }}</a-button>
            <!-- <a-upload accept=".bpmn,.xml" :custom-request="handleUpload">
              <template #upload-button>
                <a-button type="primary">
                  <template #icon><icon-upload /></template>
                  {{ $t('common.importFile') }}
                </a-button>
              </template>
            </a-upload> -->
            <a-popconfirm :content="$t('common.deleteTip')" @ok="handleBatchDelete">
              <a-button status="danger" :disabled="selectedKeys.length === 0">
                <template #icon><icon-delete /></template>
                {{ $t('common.batchDelete') }}
              </a-button>
            </a-popconfirm>
          </a-button-group>
          <a-pagination :total="pagination.total" :current="pagination.current" :page-size="pagination.pageSize"
            show-total show-jumper @change="onPageChange" />
        </div>
      </template>
    </a-table>

    <!-- 流程图查看弹窗 -->
    <a-modal v-model:visible="previewVisible" title="流程图" :mask-closable="true" width="1400px"
      @before-close="data = null">
      <BpmnModeler ref="bpmnViewer" :xmlStr="data" :version="versionTag" style="height: 60vh;" />
      <template #footer>
        <div class="table-footer">
          <a-button-group>
            <a-button type="primary" v-if="mode == 'edit'" @click="handleSave">
              {{ t('common.deploy') }}
            </a-button>
            <a-button @click="previewVisible = false">
              {{ t('common.cancel') }}
            </a-button>
          </a-button-group>
        </div>
      </template>
    </a-modal>

    <!-- 启动流程弹窗 -->
    <a-modal v-model:visible="processVisible" title="启动流程" :mask-closable="true" width="500px"
      @before-close="handleCloseProcess">
      <a-form :model="dataForm" ref="dataFormRef" :rules="dataFormRules">
        <a-form-item field="processDefinitionKey" :label="$t('workflow.processDefinition.columns.key')">
          <a-input v-model="dataForm.processDefinitionKey"
            :placeholder="$t('common.inputPlaceholder') + $t('workflow.processDefinition.columns.key')" />
        </a-form-item>
        <a-form-item field="businessKey" :label="$t('workflow.processDefinition.columns.businessKey')">
          <a-input v-model="dataForm.businessKey"
            :placeholder="$t('common.inputPlaceholder') + $t('workflow.processDefinition.columns.businessKey')" />
        </a-form-item>
        <a-form-item field="variables" :label="$t('workflow.processDefinition.columns.variables')">
          <a-textarea v-model="dataForm.variables"
            :placeholder="$t('common.inputPlaceholder') + $t('workflow.processDefinition.columns.variables')" />
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="table-footer">
          <a-button-group>
            <a-button type="primary" @click="handleStartProcess">
              {{ t('common.confirm') }}
            </a-button>
            <a-button @click="processVisible = false">
              {{ t('common.cancel') }}
            </a-button>
          </a-button-group>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { Message } from '@arco-design/web-vue';
import { processDefinitionApi, processInstanceApi } from '@/api/workflow';
import BpmnModeler from '@/components/bpmn/BpmnModeler.vue';
import { useI18n } from 'vue-i18n';
import { options } from '@/api/dict';
import { useUserStore } from '@/stores/user';

const { currenUser } = storeToRefs(useUserStore())

const { t } = useI18n();
const loading = ref(false);
const setLoading = (value) => {
  loading.value = value;
};

// 查询表单
const formRef = ref();
const dataForm = ref({
  processDefinitionKey: '',
  businessKey: '',
  variables: '{}'
});
const dataFormRef = ref();
const dataFormRules = ref({
  processDefinitionKey: [
    {
      required: true,
      message: t('common.inputPlaceholder') + t('workflow.processDefinition.columns.key'),
    },
  ],
  businessKey: [
    {
      required: true,
      message: t('common.inputPlaceholder') + t('workflow.processDefinition.columns.businessKey'),
    },
  ],
  variables: [
    {
      required: true,
      message: t('common.inputPlaceholder') + t('workflow.processDefinition.columns.variables'),
    },
  ],
});
const data = ref(null);
const mode = ref('view');
const versionTag = ref(null);
const queryForm = reactive({
  name: '',
  key: '',
  status: null
});

// 加载字典信息
const statusOption = ref([])
const loadDict = (dictType) => {
  options({ dictType: dictType }).then(res => {
    if (res.code === 200) {
      statusOption.value = res.data
    }
  })
}

// 表格数据
const tableData = ref([]);
const selectedKeys = ref([]);

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
});

// 表格选择配置
const rowSelection = {
  type: 'checkbox',
  showCheckedAll: true,
};

// 预览相关
const previewVisible = ref(false);
const processVisible = ref(false);
const bpmnViewer = ref();

const openProcessModel = async (record) => {
  dataForm.value = {
    processDefinitionKey: record.key,
    businessKey: '',
    variables: '{}'
  };
  processVisible.value = true;
};

const handleCloseProcess = () => {
  dataForm.value = {
    processDefinitionKey: '',
    businessKey: '',
    variables: '{}'
  };
  processVisible.value = false;
};

const handleStartProcess = async () => {
  try {
    const variables = JSON.parse(dataForm.value.variables);
    await processInstanceApi.startProcess({
      processDefinitionKey: dataForm.value.processDefinitionKey,
      businessKey: dataForm.value.businessKey,
      variables: variables,
      user: currenUser.value.id
    });
    Message.success(t('common.operateSuccess'));
    processVisible.value = false;
    search();
  } catch (error) {
    Message.error(error.message || t('common.operateFailed'));
  }
};

// 查询方法
const search = async () => {
  setLoading(true);
  try {
    const res = await processDefinitionApi.getList({
      ...queryForm,
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
    });
    tableData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    Message.error(error.message);
  } finally {
    setLoading(false);
  }
};

// 选择变化
const onSelectionChange = (selection) => {
  selectedKeys.value = selection;
};

// 分页变化
const onPageChange = (page) => {
  pagination.current = page;
  search();
};

const handlEdit = async (record) => {
  processDefinitionApi.getXml(record.id)
    .then(res => {
      data.value = res.data;
      mode.value = 'edit';
      versionTag.value = record.version;
      previewVisible.value = true;
    })
};

const handleView = async (record) => {
  processDefinitionApi.getXml(record.id)
    .then(res => {
      data.value = res.data;
      mode.value = 'view';
      versionTag.value = record.version;
      previewVisible.value = true;
    })
};

const handleChangeStatus = async (record) => {
  processDefinitionApi.updateState({ processDefinitionId: record.id, suspensionState: record.suspensionState })
    .then(res => {
      Message.success(t('common.operateSuccess'));
      search();
    })
};


// 下载流程文件
const handleDownload = async (record) => {
  try {
    const res = await processDefinitionApi.getXml(record.id);
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.download = `${record.name}.bpmn`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    Message.error(t('common.downloadFailed'));
  }
};

// 删除
const handleDelete = async (record) => {
  await processDefinitionApi.batchDelete({ "processDefinitionIds": record.id });
  Message.success(t('common.operateSuccess'));
  selectedKeys.value = [];
  search();
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedKeys.value.length === 0) {
    Message.warning(t('common.chooseDeleteItem'));
    return;
  }
  try {
    console.log(selectedKeys.value.join(','))
    await processDefinitionApi.batchDelete({ "processDefinitionIds": selectedKeys.value.join(',') });
    Message.success(t('common.operateSuccess'));
    selectedKeys.value = [];
    search();
  } catch (error) {
    Message.error(t('common.deleteFailed'));
  }
}

// 清空查询条件
const clear = () => {
  formRef.value.resetFields()
  search();
}

const openEditModal = () => {
  mode.value = 'edit';
  versionTag.value = null;
  previewVisible.value = true;
}

const handleSave = () => {
  nextTick(() => {
    bpmnViewer.value.saveXml().then(res => {
      if (res) {
        Message.success(t('common.operateSuccess'));
        previewVisible.value = false;
        search();
      }
    })
  });
}


onMounted(() => {
  search();
  loadDict('workflow_status');
})

</script>

<style lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.query-form {
  background-color: var(--color-bg-2);
  border-radius: 2px;
  margin-bottom: 16px;

  :deep(.arco-form-item) {
    margin-bottom: 16px;
  }

  .arco-btn-group {
    margin-top: 4px;
  }
}

.table-footer {
  display: flex;
  justify-content: end;
  align-items: center;
  padding: 8px 0;
}

.bpmn-viewer {
  height: 600px;
  width: 100%;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
</style>